from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional, List
from app.database import get_db
from app import models, schemas, auth

router = APIRouter(prefix="/agents", tags=["Agent"])


@router.get("", response_model=schemas.Response)
async def list_agents(
    category_id: Optional[int] = Query(None),
    q: Optional[str] = Query(None, description="搜索关键词"),
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    sort: str = Query("created_at", description="排序字段"),
    db: Session = Depends(get_db)
):
    """获取Agent列表"""
    query = db.query(models.Agent).filter(models.Agent.enabled == True)
    
    # 分类过滤
    if category_id:
        query = query.join(models.AgentCategory).filter(
            models.AgentCategory.category_id == category_id
        )
    
    # 搜索
    if q:
        query = query.filter(
            (models.Agent.name.like(f"%{q}%")) |
            (models.Agent.description.like(f"%{q}%"))
        )
    
    # 排序
    if sort == "hot":
        query = query.order_by(models.Agent.is_hot.desc(), models.Agent.created_at.desc())
    elif sort == "new":
        query = query.order_by(models.Agent.created_at.desc())
    else:
        query = query.order_by(models.Agent.created_at.desc())
    
    # 分页
    total = query.count()
    agents = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return schemas.Response(
        data={
            "items": [schemas.AgentResponse.from_orm(agent) for agent in agents],
            "total": total,
            "page": page,
            "page_size": page_size
        }
    )


@router.get("/{agent_id}", response_model=schemas.Response)
async def get_agent(agent_id: int, db: Session = Depends(get_db)):
    """获取Agent详情"""
    agent = db.query(models.Agent).filter(
        models.Agent.id == agent_id,
        models.Agent.enabled == True
    ).first()
    
    if not agent:
        raise HTTPException(status_code=404, detail="Agent不存在")
    
    return schemas.Response(data=schemas.AgentResponse.from_orm(agent))

